/**
 * 
 */
package com.huarui.desktop;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.TreeSet;

import net.sf.json.JSONObject;

import org.apache.commons.lang.xwork.StringUtils;
import org.ewaf.framework.action.BaseAction;

import com.huarui.desktop.model.Desktop;
import com.huarui.desktop.model.DesktopJsModule;
import com.huarui.desktop.model.DesktopMenu;
import com.huarui.desktop.service.DesktopService;
import com.huarui.task.model.WorkflowInfo;
import com.huarui.task.service.provider.WorkflowInfoProvider;
import com.huarui.user.model.SessionMessage;
import com.huarui.user.security.UserHolder;
import com.opensymphony.xwork2.Action;

/**
 * @author peng.sunp
 * 
 */
public class DesktopNewAction extends BaseAction {

	private static final long serialVersionUID = -8341798939217613812L;
	private static final String[] contantNames = { "project.name", "homeUrl",
			"appUrl", "resUrl", "searchUrl", "extjsUrl", "deskUrl",
			"deskModulesUrl", "anonymousUerHomeUrl", "registCorpUrl",
			"orderServiceUrl", "web.domain", "web.path.root", "web.path.js",
			"web.path.img", "web.path.css", "web.path.html", "url.home" };
	private DesktopService desktopService;
	private WorkflowInfoProvider workflowInfoProvider;
	private Desktop desktop;
	private JSONObject menus;
	private JSONObject launchers;
	private List<DesktopJsModule> modules;

	public String execute() throws Exception {
		// 测试时使用，设置公司的类型
		// UserHolder.getCurrentSessionMessage().setCompanyType(1);
		// UserHolder.getCurrentSessionMessage().setEmployeeId(1);
		this.desktop = this.desktopService.getOwnDesktop();
		if (this.desktop == null) {
			return "error";
		}
		Integer desktopId = this.desktop.getId();
		Map<Integer, DesktopMenu> desktopMenus = this.desktopService
				.getDesktopMenus(desktopId);
		this.menus = JSONObject
				.fromObject(desktopMenus, DesktopMenu.jsonConfig);
		this.modules = this.desktopService.getOwnDesktopJsModules(desktopId,
				desktopMenus.values());
		this.launchers = this.genLanuchers(this.modules);
		return Action.SUCCESS;
	}

	public Desktop getDesktop() {
		return this.desktop;
	}

	public JSONObject getMenus() {
		return this.menus;
	}

	public List<DesktopJsModule> getModules() {
		return this.modules;
	}

	public JSONObject getLaunchers() {
		return this.launchers;
	}

	public List<Integer> getPermissions() {
		List<Integer> permissions = this.desktopService.getOwnPermissionIds();
		Collections.sort(permissions);
		return permissions;
	}

	public JSONObject getConstants() {
		Properties env = this.getEnv();
		Properties p = new Properties();
		for (String key : DesktopNewAction.contantNames) {
			if (env.containsKey(key)) {
				p.setProperty(key, env.getProperty(key));
			}

		}
		return JSONObject.fromObject(p);
	}

	public String getUserName() {
		SessionMessage sessionMessage = UserHolder.getCurrentSessionMessage();
		return sessionMessage.getUserName();
	}

	public JSONObject getWorkflowModules() {
		JSONObject workflowModules = null;
		Map<String, WorkflowInfo> infoes = this.workflowInfoProvider
				.getInfoes();
		if (infoes != null && infoes.size() > 0) {
			workflowModules = new JSONObject();
			for (WorkflowInfo info : infoes.values()) {
				workflowModules.put(info.getTaskNameEn(), info.getJsModuleId());
			}
		}
		return workflowModules;

	}

	protected JSONObject genLanuchers(List<DesktopJsModule> modules) {
		JSONObject launchers = new JSONObject();
		List<String> stylesheets = new ArrayList<String>();

		List<String> autoruns = new ArrayList<String>();
		List<String> quickstarts = new ArrayList<String>();
		List<String> shortcuts = new ArrayList<String>();

		TreeSet<DesktopJsModule> quickstartModules = new TreeSet<DesktopJsModule>(
				new Comparator<DesktopJsModule>() {
					@Override
					public int compare(DesktopJsModule m1, DesktopJsModule m2) {
						Integer m1Seq = m1.getQuickstartSeq();
						Integer m2Seq = m2.getQuickstartSeq();
						return m1Seq == null ? 1 : (m2Seq == null ? -1 : (m1Seq
								.equals(m2Seq) ? 1 : m1Seq.compareTo(m2Seq)));
					}
				});
		TreeSet<DesktopJsModule> shortcutModules = new TreeSet<DesktopJsModule>(
				new Comparator<DesktopJsModule>() {
					@Override
					public int compare(DesktopJsModule m1, DesktopJsModule m2) {
						Integer m1Seq = m1.getShortcutSeq();
						Integer m2Seq = m2.getShortcutSeq();
						return m1Seq == null ? 1 : (m2Seq == null ? -1 : (m1Seq
								.equals(m2Seq) ? 1 : m1Seq.compareTo(m2Seq)));
					}
				});

		String prefix = this.getEnv().getProperty("deskModulesUrl");
		for (DesktopJsModule module : modules) {
			module.setScriptUrl(fullModuleUrl(module.getScriptUrl(), prefix));

			String stylesheetUrl = module.getStylesheetUrl();
			if (StringUtils.isNotEmpty(stylesheetUrl)) {
				stylesheets.add(fullModuleUrl(stylesheetUrl, prefix));
			}

			if (module.isAutorun()) {
				autoruns.add(module.getModuleId());
			}

			if (module.isInQuickstart()) {
				quickstartModules.add(module);

			}
			if (module.isInShortcut()) {
				shortcutModules.add(module);
			}
		}
		for (DesktopJsModule module : quickstartModules) {
			quickstarts.add(module.getModuleId());
		}
		for (DesktopJsModule module : shortcutModules) {
			shortcuts.add(module.getModuleId());
		}
		launchers.put("stylesheets", stylesheets);
		launchers.put("autoruns", autoruns);
		launchers.put("quickstarts", quickstarts);
		launchers.put("shortcuts", shortcuts);
		return launchers;
	}

	protected String fullModuleUrl(String url, String prefix) {
		if (StringUtils.isEmpty(url)) {
			return url;
		}
		if (StringUtils.startsWithIgnoreCase(url, "http")
				|| StringUtils.startsWithIgnoreCase(url, prefix)) {
			return url;
		} else {
			return prefix + url;
		}
	}

	public void setDesktopService(DesktopService desktopService) {
		this.desktopService = desktopService;
	}

	public void setWorkflowInfoProvider(
			WorkflowInfoProvider workflowInfoProvider) {
		this.workflowInfoProvider = workflowInfoProvider;
	}

}
